import { defineComponent } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { BasicModal, useModalInner } from '@/components/Modal';
import { useMessage } from '@/hooks/web/useMessage';
import { reserveSeatApi, updateReserveSeatApi } from '../service';
import { getStudyRoomListApi } from '../../studyRoom/service';
import dayjs from 'dayjs';
import { useUserStore } from '/@/store/modules/user';

export default defineComponent({
  name: 'ActionModal',
  emits: ['register', 'reload'],
  setup(_, { emit }) {
    const {
      createMessage: { success },
    } = useMessage();

    const { UserID, UserName }: any = useUserStore().getUserInfo;
    const [registerModal, { changeLoading, changeOkLoading, closeModal, setModalProps }] =
      useModalInner(async ({ record, type = 'add' }) => {
        changeLoading(true);
        changeOkLoading(true);
        setModalProps({ title: `${type === 'add' ? '新增' : '编辑'}预约` });
        if (type === 'edit') {
          const [TimeStart, TimeEnd] = record.Time.split('-');
          await setFieldsValue(
            { ...record, TimeStart: dayjs(TimeStart, 'HH:mm'), TimeEnd: dayjs(TimeEnd, 'HH:mm') } ||
              {},
          );
        }
        changeLoading(false);
        changeOkLoading(false);
      });

    const [registerForm, { validate, setFieldsValue }] = useForm({
      labelWidth: 100,
      baseColProps: { span: 24 },
      schemas: [
        {
          field: 'ReserveSeatID',
          label: 'ReserveSeatID',
          show: false,
          component: 'Input',
        },
        {
          field: 'RoomID',
          label: '自习室',
          component: 'ApiSelect',
          required: true,
          componentProps: ({ formModel }) => ({
            api: async () => {
              const res = await getStudyRoomListApi({ page: 1, pageSize: 100 });
              formModel.studyRoomOptions = res.data.records;
              return res.data;
            },
            resultField: 'records',
            labelField: 'RoomName',
            valueField: 'RoomID',
            onChange: (RoomID) => {
              // 从暂存的选项中查找对应RoomName
              const target = (formModel.studyRoomOptions || []).find(
                (item) => item.RoomID === RoomID,
              );
              // 设置RoomName字段值
              formModel.RoomName = target?.RoomName || '';
            },
          }),
        },
        {
          field: 'RoomName',
          label: '自习室名称',
          component: 'Input',
          required: true,
          show: false,
        },
        {
          field: 'Date',
          label: '使用日期',
          component: 'DatePicker',
          componentProps: {
            style: 'width:100%',
            disabledDate: (current: any) => {
              return current && current < new Date().setHours(0, 0, 0, 0);
            },
            placeholder: '请选择使用日期',
          },
          required: true,
        },
        {
          field: 'TimeStart',
          label: '开始时间段',
          component: 'TimePicker',
          componentProps: ({ formModel, formActionType }) => ({
            style: 'width:100%',
            placeholder: '请选择开始使用时间',
            onChange: (TimeStart) => {
              formActionType?.updateSchema({
                field: 'TimeEnd',
                componentProps: {
                  disabledHours: (current) => {
                    const startHour = dayjs(TimeStart).get('hour');
                    function getIntegersLessThan(num) {
                      let result: any = [];
                      for (let i: any = 0; i < num; i++) {
                        result.push(i);
                      }
                      return result;
                    }
                    return getIntegersLessThan(startHour);
                  },
                },
              });
              if (TimeStart) {
                formModel.TimeEnd = null;
              }
            },
          }),
          required: true,
        },
        {
          field: 'TimeEnd',
          label: '结束时间段',
          component: 'TimePicker',
          componentProps: {
            style: 'width:100%',
            placeholder: '请选择结束使用时间',
          },
          dynamicDisabled: ({ values }: any) => {
            return !values.TimeStart;
          },
          required: true,
        },
      ],
      showActionButtonGroup: false,
    });

    const handleSubmit = async () => {
      changeLoading(true);
      changeOkLoading(true);

      try {
        const values = await validate();
        const req = {
          ...values,
          UserID,
          UserName,
          Date: dayjs(values.Date).format('YYYY-MM-DD'),
          Time:
            dayjs(values.TimeStart).format('HH:mm') + '-' + dayjs(values.TimeEnd).format('HH:mm'),
        };
        if (!values.ReserveSeatID) {
          await reserveSeatApi(req);
          success('预约成功');
        } else {
          await updateReserveSeatApi(req);
          success('更新成功');
        }
        closeModal();
        emit('reload');
      } finally {
        changeLoading(false);
        changeOkLoading(false);
      }
    };

    return () => (
      <BasicModal
        width={600}
        minHeight={300}
        onRegister={registerModal}
        destroyOnClose
        onOk={handleSubmit}
      >
        <div class="px-4">
          <BasicForm onRegister={registerForm} />
        </div>
      </BasicModal>
    );
  },
});
